package reduce.fz.com.reduce.util;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.RoundRectShape;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.widget.Toast;


import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.concurrent.atomic.AtomicInteger;

import reduce.fz.com.reduce.util.base.ReduceApplication;


/**
 * 工具类
 * @author lipf
 */
public class Utils {

    private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);

    /**
     * 获取渠道号
     * @return
     */
    public static String getChannel(){
        try {
            ApplicationInfo appInfo = ReduceApplication.getInstance().getPackageManager()
                    .getApplicationInfo(ReduceApplication.getInstance().getPackageName(),
                            PackageManager.GET_META_DATA);
            String channel = appInfo.metaData.getString("UMENG_CHANNEL");
            return channel;
        }catch (Throwable e){
            return null;
        }
    }

    public static String getPhoneModel(){
        try{
            return Build.MODEL;
        }catch (Throwable e){
            return "";
        }
    }

    public static int generateViewId() {
        for (; ; ) {
            final int result = sNextGeneratedId.get();
            int newValue = result + 1;
            if (newValue > 0x00FFFFFF)
                newValue = 1;
            if (sNextGeneratedId.compareAndSet(result, newValue)) {
                return result;
            }
        }
    }

    public static String getDeviceName() {
        String manufacturer = Build.MANUFACTURER;
        String model = Build.MODEL;
        if (model.startsWith(manufacturer)) {
            return capitalize(model);
        } else {
            return capitalize(manufacturer) + " " + model;
        }
    }

    private static String capitalize(String s) {
        if (TextUtils.isEmpty(s))
            return "";

        char first = s.charAt(0);
        if (Character.isUpperCase(first)) {
            return s;
        } else {
            return Character.toUpperCase(first) + s.substring(1);
        }
    }

    public static void showToast(String msg) {
        try{
            if(msg==null){
                return;
            }
            Toast.makeText(ReduceApplication.getInstance(), msg, Toast.LENGTH_SHORT).show();
        }catch (Exception e){
            ReduceLog.e(e);
        }
    }

    public static void showToast(int resId) {
        try{
            showToast(ReduceApplication.getInstance().getString(resId));
        }catch (Exception e){
            ReduceLog.e(e);
        }
    }

    public static void showToast(final Context context ,final String msg ) {
        try{
            if(msg==null){
                return;
            }
            Toast.makeText( context, msg, Toast.LENGTH_SHORT).show();
        }catch (Exception e){
            ReduceLog.e(e);
        }
    }

    public static void showToast( final Context context , final int msgId ) {
        try{
            Toast.makeText( context , msgId , Toast.LENGTH_SHORT ).show();
        }catch (Throwable e){
            ReduceLog.e(e);
        }
    }

    public static Bitmap zoomBitmap(Bitmap bitmap, int w, int h) {
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        Matrix matrix = new Matrix();
        float scaleWidth = ((float) w / width);
        float scaleHeight = ((float) h / height);
        matrix.postScale(scaleWidth, scaleHeight);
        Bitmap newBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height,
                matrix, true);
        return newBitmap;
    }

    /**
     * 等比例缩放
     * @param bitmap
     * @param toW
     * @return
     */
    public static Bitmap ratioWidthBitmap(Bitmap bitmap, int toW ){
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        float scaleWidth = ((float) toW / width);
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleWidth);
        Bitmap newBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height,
                matrix, true);
        return newBitmap;
    }

    public static ShapeDrawable getShapeDrawable(int color, int radius) {
        RoundRectShape roundRectShape = new RoundRectShape(new float[] { radius, radius, radius, radius, radius, radius, radius, radius }, null, null);
        ShapeDrawable shapeDrawable = new ShapeDrawable(roundRectShape);
        shapeDrawable.getPaint().setColor(color);
        return shapeDrawable;
    }

    public static synchronized boolean didNetworkConnected(Context context) {
        ConnectivityManager conn = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (null != conn) {
            NetworkInfo info = conn.getActiveNetworkInfo();
            if (null != info) return info.isConnected();
        }
        return false;
    }

    public static synchronized boolean isWifiConnected(Context context) {
        ConnectivityManager connManager = (ConnectivityManager) context.getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connManager != null) {
            NetworkInfo networkInfo = connManager.getActiveNetworkInfo();
            if (networkInfo != null) {
                int networkInfoType = networkInfo.getType();
                if (networkInfoType == ConnectivityManager.TYPE_WIFI || networkInfoType == ConnectivityManager.TYPE_ETHERNET) {
                    return networkInfo.isConnected();
                }
            }
        }
        return false;
    }

    public static String getVersionName(Context context) {
        String versionName = "";
        Context appContext = context.getApplicationContext();

        try {
            PackageManager pm = appContext.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(appContext.getPackageName(), 0);
            versionName = pi.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        return versionName;
    }

    /**
     * 将版本里面的 . 替换成 _
     * @param context
     * @return
     */
    public static String getVersionNameWithoutPoint(Context context){
        String versionName = getVersionName(context);
        return versionName.replace(".","_");
    }

    public static int getVersionCode(Context context) {
        int versionCode = 0;
        Context appContext = context.getApplicationContext();

        try {
            PackageManager pm = appContext.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(appContext.getPackageName(), 0);
            versionCode = pi.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        return versionCode;
    }

    public static int getAndroidSDKVersion() {
        try{
            return Build.VERSION.SDK_INT;
        }catch (Throwable e){
            return 0;
        }
    }

    public static void runWithoutMessage(final Runnable action, final Runnable postAction) {
        final Handler handler = new Handler() {
            public void handleMessage(Message message) {
                postAction.run();
            }
        };

        final Thread runner = new Thread(new Runnable() {
            public void run() {
                action.run();
                handler.sendEmptyMessage(0);
            }
        });
        runner.setPriority(Thread.MIN_PRIORITY);
        runner.start();
    }

    public static String readFromAssets(Context context, String name) {
        if (null == context) return null;

        InputStream is;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            is = context.getAssets().open(name);
            byte buf[] = new byte[1024];
            int len;
            while ((len = is.read(buf)) != -1) {
                baos.write(buf, 0, len);
            }
            baos.close();
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return baos.toString();
    }

    public static <T> Collection<T> nullSafe(Collection<T> c) {
        return (null == c) ? Collections.<T>emptyList() : c;
    }

    public static Bitmap toCircleBitmap(Bitmap bitmap) {
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setFilterBitmap(false);
        int w = bitmap.getWidth();
        int h = bitmap.getHeight();

        Bitmap bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        int r = Math.min(w / 2, h / 2);
        Canvas canvas = new Canvas(bmp);
        canvas.drawCircle(r, r, r, paint);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(bitmap, 0, 0, paint);
        paint.setXfermode(null);
        bitmap = null;

        return bmp;
    }

    /**
     * 判断是否是图片
     * @param fileName
     * @return
     */
    public static boolean isImage(String fileName){
        String fn = fileName.toLowerCase();
        return fn.endsWith(".jpg") || fn.endsWith(".jpeg") || fn.endsWith(".png") || fn.endsWith(".gif");
    }

    public static int getAge(String birthDate){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date date = new Date();
            int curYear = date.getYear();
            date = sdf.parse(birthDate);
            int birthYear = date.getYear();
            int age = curYear - birthYear;
            if(age<0)
                age = 0;
            return age;
        }catch (Exception e){

        }
        return 0;
    }

    /**
     * 根据年份获取年龄
     * @param birthYear
     * @return
     */
    public static int getAge(int birthYear){
        try {
            Calendar now = Calendar.getInstance();
            int curyear = now.get(Calendar.YEAR);
            int age = curyear - birthYear;
            if(age<0)
                age = 0;
            return age;
        }catch (Exception e){

        }
        return 0;
    }

    public static String getBirthdayStr(int year, int monthOfYear, int dayOfMonth){
        monthOfYear = monthOfYear+1;
        return year + "-" + (monthOfYear>9?monthOfYear:("0"+monthOfYear)) + "-" + (dayOfMonth>9?dayOfMonth:("0"+dayOfMonth));
    }
}
